<template>
    <div>
        <div class="p-4">
            <el-form :inline="true" :model="searchParams" class="demo-form-inline">
                <el-form-item label="关键字搜索">
                    <el-input v-model="searchParams.nameKeyword" placeholder="名称/电话" clearable />
                </el-form-item>
                <el-form-item label="性别">
                    <el-select v-model="searchParams.sex" placeholder="选择性别" style="width: 120px" clearable>
                        <el-option label="全部" value="" />
                        <el-option label="男" value="男" />
                        <el-option label="女" value="女" />
                        <el-option label="保密" value="保密" />
                    </el-select>
                </el-form-item>
                <el-form-item label="添加时间">
                    <el-date-picker v-model="searchParams.createTime" type="date" format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD" placeholder="入职时间" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="getList">搜索</el-button>
                </el-form-item>
            </el-form>
            <div class="mt-3">
                <el-button v-if="btnShow('001')" type="primary" icon="Plus" @click="add">新增</el-button>
                <el-button v-if="btnShow('004')" type="danger" icon="Delete" @click="bachRemove">批量注销</el-button>
            </div>
            <div class="mt-3">
                <el-table ref="tableRef" :data="data" border style="width: 100%">
                    <el-table-column align="center" type="selection" :selectable="selectable" width="55" />
                    <el-table-column align="center" type="index" :index="indexMethod" label="序号" width="60" />
                    <el-table-column align="center" fit v-for="(item,index) in columns" :key="index" :prop="item.key"
                        :label="item.title" :formatter="item.formatter" :width="item.width" />
                    <el-table-column fixed="right" fit align="center" label="操作">
                        <template #default="scope">
                            <el-button v-if="btnShow('002')" link type="primary" size="small" @click="edit(scope.row)">编辑</el-button>
                            <el-button v-if="btnShow('003')" link type="danger" size="small" @click="del(scope.row)">注销</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="mt-3">
                <el-pagination v-model:current-page="searchParams.pageNumber" v-model:page-size="searchParams.pageSize"
                    :page-sizes="[10, 20, 30, 50]" :background="background"
                    layout="total, sizes, prev, pager, next, jumper" :total="totalRow" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </div>

        <!-- 添加与编辑 -->
        <el-dialog v-model="addDialog" :title="isAdd?'添加':('编辑员工： '+ editItem.userName)" width="60%" center>

            <!-- 编辑表单信息 -->
            <el-form label-width="auto" ref="editItemRef" :model="editItem" :rules="editItemRules" class="demo-ruleForm"
                status-icon>
                <el-form-item label="登录账号" prop="loginName">
                    <el-input v-model="editItem.loginName" clearable />
                </el-form-item>
                <el-form-item label="员工姓名" prop="userName">
                    <el-input v-model="editItem.userName" clearable />
                </el-form-item>
                <el-form-item label="联系电话" prop="userTele">
                    <el-input v-model="editItem.userTele" clearable />
                </el-form-item>
                <el-form-item label="性别">
                    <el-select v-model="editItem.sex" placeholder="选择性别" clearable>
                        <el-option label="男" value="男" />
                        <el-option label="女" value="女" />
                        <el-option label="保密" value="保密" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所属部门">
                    <el-select v-model="editItem.deptId" placeholder="所属部门">
                        <el-option label="暂无" :value="parseInt('0')" />
                        <el-option v-for="item in sysDepts" :key="item.id" :label="item.deptName"
                            :value="parseInt(item.id)" />
                    </el-select>
                </el-form-item>
                <el-form-item label="角色类型">
                    <el-select v-model="editItem.roleId" placeholder="角色类型">
                        <el-option label="暂无" :value="parseInt('0')" />
                        <el-option v-for="item in sysRoles" :key="item.id" :label="item.roleName"
                            :value="parseInt(item.id)" />
                    </el-select>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="addDialog = false">取消</el-button>
                    <el-button type="primary" @click="save(editItemRef)">保存</el-button>
                </div>
            </template>
        </el-dialog>


        <!-- 操作提示弹框 -->
        <el-dialog v-model="openDialog" title="操作提示" width="40%" center>
            <span class="m-t-10 m-b-10">{{ openDialogTitle }}</span>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="openDialog = false">取消</el-button>
                    <el-button type="primary" @click="confirm">确认</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>


<script setup>
import { indexMethod, getSysDepts, getSysRoles } from '@/config/utils';
import { ref } from 'vue';
import { getUsers, getBtnList, checkLoginName, saveUser } from '@/config/api.js'
//获取当前路由信息
import { useRoute } from 'vue-router';
const route = useRoute();
//获取按钮权限
const btns = ref([])
const getBtns = () => {
    let data = {
        path: route.path
    }
    getBtnList(data).then(res => {
        btns.value = res.data
    })
}
getBtns();
const btnShow = (codeNo) => {
    let flag = btns.value.includes(codeNo);
    return flag
}


//搜索条件
const totalRow = ref(0)
const searchParams = ref({
    pageNumber: 1,
    pageSize: 10
})

//表格数据
const tableRef = ref()
const data = ref([])
//表格数据列名称
const columns = ref([
    {
       key: 'userName',
       title: '员工姓名',
   },
   {
       key: 'loginName',
       title: '登录账号',
   },
   {
       key: 'userTele',
       title: '联系方式',
   },
   {
       key: 'sex',
       title: '性别',
   },
    {
        key: 'deptName',
        title: '所属部门',
    },
    {
        key: 'roleName',
        title: '角色类型',
    },
    {
        key: 'createTime',
        title: '入职时间',
    }
])

const selectable = ref()
//获取数据
function getList(){
    //执行查询数据
    getUsers(searchParams.value).then(res => {
        if(res.code == 200){
            data.value = res.data.records
            totalRow.value = res.data.totalRow
        }
    })
}

//分页参数处理
const handleSizeChange = (e) => {
    searchParams.value.pageSize = e
    getList()
}
const handleCurrentChange = (e) => {
  searchParams.value.pageNumber = e
  getList()
}
getList();

//校验规则
function checkName(rule, value, callback) {
    if (!value || value === '') {
        callback(new Error('登录账号必填'))
    } else {
        let data = {
            loginName: value,
            userId: editItem.value.id
        }
        checkLoginName(data).then(res => {
            if (res.code == 200) {
                callback()
            }
            else {
                callback(new Error(res.msg))
            }
        })
    }
}
function checkTele(rule, value, callback){
    if (!value || value === '') {
        callback(new Error('联系电话不能为空'))
    } else {
       //kind: 1.系统管理员添加店铺主账号 2.店铺自主注册 3.店铺添加员工
       let data = {
           kind: 3,
           tele: value,
           userId: editItem.value.id
       }
       checkUserTele(data).then(res => {
           if(res.code == 200){
               callback()
           }
           else{
               callback(new Error(res.msg))
           }
       })
   }
}

//添加与编辑员工
const editItem = ref({})
const addDialog = ref(false)
const editItemRef = ref()

const editItemRules = ref({
    loginName: [
        { required: true, message: '登录账号必填', trigger: 'blur' },
        { validator: checkName, trigger: 'blur' }
    ],
    userName: [
        {required: true, message: '员工姓名必填', trigger: 'blur'}
    ],
    userTele: [
        {required: true, message: '联系电话必填', trigger: 'blur'}
    ],
})
//打开操作页面
const isAdd = ref(true)
// 获取系统部门
const sysDepts = ref([])
// 获取系统部门
const sysRoles = ref([])

//添加
const add = async () => {
    addDialog.value = true
    editItem.value = {}
    sysDepts.value = await getSysDepts(0);
    sysRoles.value = await getSysRoles();
}
//编辑员工
const edit = async (item) => {
    addDialog.value = true
    sysDepts.value = await getSysDepts(0);
    sysRoles.value = await getSysRoles();
    editItem.value = item
}

//保存信息
const save = (itemRef) => {
    if (!itemRef) return
    itemRef.validate((valid) => {
        if (valid) {
            saveUser(editItem.value).then(res => {
                if(res.code == 200){
                    addDialog.value = false
                    ElMessage.success('添加成功')
                    getList();
                }
            })
        } else {
            ElMessage.error('表单校验未通过')
        }
    })
}


//删除
const openKind = ref({})
const openDialog = ref(false)
const openDialogTitle = ref('')
const openItem = ref({})
//单条删除
const del = (item) => {
    openDialog.value = true
    openKind.value = 1
    openDialogTitle.value = "确认要注销员工账号：" + item.userName + " ?"
    openItem.value = item
}
//批量删除
const bachRemove = () => {
    const list = tableRef.value.getSelectionRows();
    console.log('选中的数据 ==> {}', list);
    if(list.length <= 0){
        ElMessage.error('请先选择要操作的数据')
        return
    }
    openDialog.value = true
    openKind.value = 2
    openDialogTitle.value = "确认要注销选中的员工？"
}

//提交确认信息
const confirm = () => {
    if(openKind.value == 1){
        console.log('删除了 ==> {}', openItem.value.roleName);
    }
    else if(openKind.value == 2){
        const list = tableRef.value.getSelectionRows();
        const ids = list.map(item => item.id);
        const names = list.map(item => item.roleName);
        console.log('执行批量删除 ==> {}', ids);
        console.log('执行批量删除 ==> {}', names);
    }
    openDialog.value = false
}
</script>


<style scoped>

</style>